package com.itheima.reggie.common;

import com.itheima.reggie.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.sql.SQLIntegrityConstraintViolationException;


// @ControllerAdvice 参数传入annotation,controller的class
// 需要给客户端响应数据,所以需要 @responseBody  保证传回去的是json字符串
@ControllerAdvice(annotations = {RestController.class,Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    // 注解ExceptionHandler(异常的class)
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R exceptionHandler(SQLIntegrityConstraintViolationException e) {
        // 用日志记录犯下的异常记录msg
        log.info("异常的信息{}",e.getMessage());
        // 先找到包含Duplicate entry的项,再使用字符串的split切割,这样第3个就是异常原因的名字
        if (e.getMessage().contains("Duplicate entry")) {
            String[] s = e.getMessage().split(" ");
            // 字符串拼接"已存在"
            String msg = s[2] + "已存在";
            // 使用R返回结果
            return R.error(msg);
        }

        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R customExceptionHandler(CustomException e) {
        log.warn("出现了业务异常:{}",e.getMessage());
        return R.error(e.getMessage());
    }

}
